// 图片处理 Worker
self.onmessage = function(e) {
    const { file, canvasWidth, canvasHeight } = e.data;

    const reader = new FileReader();

    reader.onload = function(event) {
        const imgUrl = event.target.result;

        // 使用 createImageBitmap 替代 Image
        fetch(imgUrl)
            .then(response => response.blob())
            .then(blob => createImageBitmap(blob))
            .then(imageBitmap => {
                // 计算缩放比例
                let width = imageBitmap.width;
                let height = imageBitmap.height;

                // 限制最大尺寸为画布的40%
                const maxWidth = canvasWidth * 0.4;
                const maxHeight = canvasHeight * 0.4;

                // 计算宽高比
                const aspectRatio = width / height;

                // 根据宽高比调整尺寸
                if (width > maxWidth || height > maxHeight) {
                    if (aspectRatio > 1) {
                        // 宽大于高
                        width = maxWidth;
                        height = width / aspectRatio;
                    } else {
                        // 高大于宽
                        height = maxHeight;
                        width = height * aspectRatio;
                    }
                }

                // 确保尺寸是整数
                width = Math.round(width);
                height = Math.round(height);

                // 将处理后的图片数据发送回主线程
                self.postMessage({
                    success: true,
                    imgUrl,
                    width,
                    height,
                    originalWidth: imageBitmap.width,
                    originalHeight: imageBitmap.height
                });
            })
            .catch(error => {
                self.postMessage({
                    success: false,
                    error: '图片处理失败: ' + error.message
                });
            });
    };

    reader.onerror = function() {
        self.postMessage({
            success: false,
            error: '文件读取失败'
        });
    };

    reader.readAsDataURL(file);
};